use anyhow::{anyhow, Context, Result};

use std::process::Command;
pub fn parse(url: &str) -> Result<MercuryOutput> {
    //let relative_path = env::var("MERCURY_PATH").context("Cannot find 'MERCURY_PATH' variable")?;
    //let full_path = canonicalize(relative_path).context("failed to find path")?;

    let process = Command::new("mercury-parser")
        .arg(url)
        .arg("--format=html")
        .output()
        .context("failed to start mercury process")?;
    if !process.stderr.is_empty() {
        let err = String::from_utf8(process.stderr).context("Could not parse stderr")?;
        println!("{:#?}", err);
        if err == "The url parameter passed does not look like a valid URL. Please check your URL and try again." {
            return Err(anyhow!(MercuryError::InvalidUrl))
        }
    }
    let json = String::from_utf8(process.stdout).context("cannot create string from vec<u8>")?;
    println!("{:#?}", json);
    let parsed_json =
        serde_json::from_str::<MercuryOutput>(&json).context("cannot deserialize json")?;
    println!("{:#?}", parsed_json);

    Ok(parsed_json)
}
use serde::Deserialize;
use url::Url;
#[derive(Debug, Deserialize)]
pub struct MercuryOutput {
    pub title: Option<String>,
    pub content: Option<String>,
    pub author: Option<String>,
    pub date_published: Option<String>,
    pub lead_image_url: Option<Url>,
    pub next_page_url: Option<Url>,
    pub dek: Option<String>,
    pub url: Url,
    pub domain: Option<String>,
    pub excerpt: Option<String>,
    pub word_count: Option<i64>,
    pub direction: Option<String>,
    pub total_pages: Option<i64>,
    pub rendered_pages: Option<i64>,
}
use thiserror::Error;
#[derive(Debug, Error)]
enum MercuryError {
    #[error("Parameter url is invalid")]
    InvalidUrl,
}
